import { Injectable } from '@nestjs/common';
import { CreateSpiderDto, getUrlSpiderDto } from './dto/create-spider.dto';
import { UpdateSpiderDto } from './dto/update-spider.dto';
var request = require('request');
const puppeteer = require('puppeteer');
const { Builder, By } = require('selenium-webdriver');


@Injectable()
export class SpiderService {
  create(createSpiderDto: CreateSpiderDto) {
    return 'This action adds a new spider';
  }

  async findAll() {
    let driver = await new Builder().forBrowser('chrome').build();
    // try {
    //   // Navigate to Url
    //   await driver.get('https://www.1kkk.com/ch1-1003355/#ipg2');
    //   await driver.manage().setTimeouts({ implicit: 2000 });
    //   // Get all the elements available with tag 'p'
    //   let imgs = await driver.findElements(By.id('cp_image'))
    //   //let imgs = await page.findElements(By.css('img'));
    //   for (let e of imgs) {
    //     console.log(await e.getAttribute('src'));
    //   }
    //   const next = await driver.findElement(By.className('block'))
    //   console.log(next.getText())
    //   const nestPage = async () => {
    //     const next = await driver.findElement(By.className('img_land_next'))
    //     if (next) {
    //       await next.click()
    //       //let elements = await driver.findElements(By.css('img'));
    //       let imgs = await driver.findElements(By.id('cp_image'))
    //       //let imgs = await page.findElements(By.css('img'));
    //       for (let e of imgs) {
    //         console.log(await e.getAttribute('src'))
    //       }
    //       nestPage()
    //     } else {
    //       return
    //     }
    //   }
    //   // await nestPage()



    // }
    /* 这段是爬取moe站文章图片的示例代码*/
    try {
      await driver.get('https://www.hmoeh.com/702958.html');
      await driver.findElement(By.className('poi-dialog__header__close')).click()
      let post = await driver.findElement(By.className('inn-content-reseter'));
      let imgs = await post.findElements(By.css('img'))
      for (let e of imgs) {
        console.log(await e.getAttribute('src'));
      }
    } catch (e) {
    }
    finally {
      //await driver.quit();
    }
    /* 这段是静态爬虫代码*/
    // request('http://www.baidu.com', function (error, response, body) {
    //   if (!error && response.statusCode == 200) {
    //     // 输出网页内容
    //     console.log(body);
    //   }else{
    //     console.log('error',response.statusCode)
    //   }
    // });

    return `This action returns all spider`;
  }

  async nextPage(driver, className, callBack) {
    const next = await driver.findElement(By.className(className))
    if (next) {
      await next.click()
      await callBack
      this.nextPage(driver, className, callBack)
    } else {
      return
    }
  }

  async findUrlInfo(getUrlSpiderDto:getUrlSpiderDto) {
    // 启动浏览器
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(getUrlSpiderDto.url);
    const title = await page.title();
    const description = await page.$eval(`meta[name=${JSON.stringify('description')}]`, el => el.getAttribute('content'));
    // const keywords = await page.$eval('meta[name="keywords"]', el => el.getAttribute('content'));
    // 获取网站的logo
    let logo
    try {
      logo = await page.$eval('link[rel="icon"]', el => el.getAttribute('href'));
    } catch (e) {
      // 如果超时，做一些处理。
    }
    // 输出结果
    let pageUrl = page.url()
    console.log('标题：', title);
    console.log('描述：', description);
    let reg = new RegExp('http');
    if (reg.test(logo)) {
      logo = logo
    } else {
      logo = pageUrl + logo
    }
    // 关闭浏览器
    await browser.close();
    const result = {
      title,
      description,
      logo:logo
    }
    return result
  }

  findOne(id: number) {
    initPuppeteer()
    // 初始化puppeteer
    async function initPuppeteer() {
      // 启动浏览器
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      // 访问目标网站
      const url = 'https://www.nuxt.com.cn/';
      await page.goto(url);
      const title = await page.title();
      const description = await page.$eval(`meta[name=${JSON.stringify('description')}]`, el => el.getAttribute('content'));
      // const keywords = await page.$eval('meta[name="keywords"]', el => el.getAttribute('content'));
      // 获取网站的logo
      let logo
      try {
        logo = await page.$eval('link[rel="icon"]', el => el.getAttribute('href'));
      } catch (e) {
        // 如果超时，做一些处理。
      }
      // 输出结果
      let pageUrl = page.url()
      console.log('标题：', title);
      console.log('描述：', description);
      let reg = new RegExp('http');
      if (reg.test(logo)) {
        console.log('Logo:', logo);
      } else {
        console.log('Logo:', pageUrl + logo);
      }
      // 关闭浏览器
      await browser.close();
    }
    return `This action returns a #${id} spider`;
  }

  update(id: number, updateSpiderDto: UpdateSpiderDto) {
    return `This action updates a #${id} spider`;
  }

  remove(id: number) {
    return `This action removes a #${id} spider`;
  }
}
